import React, { useState, useEffect } from 'react';
import { Dialog } from '@headlessui/react';
import {
  fetchAudits,
  createAudit,
  updateAudit,
  deleteAudit,
  fetchAuditById,
} from './auditApi';
interface AuditData {
  statutes: Array<{
    clause_number: string;
    section: string;
    content: string;
  }>;
  key_points: string[];
  department: string[];
  description: string;
}
const Audit: React.FC = () => {
  const [audits, setAudits] = useState<any[]>([]);
  const [isOpen, setIsOpen] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [formData, setFormData] = useState({
    audit_rule_id: '',
    statutes: [
      {
        clause_number: '',
        section: '',
        content: '',
      },
    ],
    key_points: '',
    department: '',
    description: '',
  });

  useEffect(() => {
    loadAudits();
  }, []);

  const loadAudits = async () => {
    try {
      const res = await fetchAudits(1, 10, '', '', '');
      if (Array.isArray(res.data)) {
        setAudits(res.data);
      } else {
        console.error('Expected an array but received:', res.data);
        setAudits([]);
      }
    } catch (error) {
      console.error('Failed to fetch audits:', error);
      setAudits([]);
    }
  };

  const handleOpenModal = (edit = false, auditId = '') => {
    if (edit) {
      setIsEdit(true);
      fetchAuditById(auditId).then((res) => {
        setFormData(res.data);
      });
    } else {
      setIsEdit(false);
      setFormData({
        audit_rule_id: '',
        statutes: [
          {
            clause_number: '',
            section: '',
            content: '',
          },
        ],
        key_points: '',
        department: '',
        description: '',
      });
    }
    setIsOpen(true);
  };

  const handleCloseModal = () => {
    setIsOpen(false);
  };

  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>, index?: number, field?: string) => {
    if (index !== undefined && field) {
      // 处理 statutes 数组中的对象更新
      const updatedStatutes = [...formData.statutes];
      updatedStatutes[index] = { ...updatedStatutes[index], [field]: e.target.value };
      setFormData({ ...formData, statutes: updatedStatutes });
    } else {
      // 处理除 statutes 数组外的其他字段更新
      setFormData({ ...formData, [e.target.name]: e.target.value });
    }
  };

  const handleSubmit = async () => {
    // 将 formData 转换为符合 AuditData 接口的格式
    const auditData: AuditData & { audit_rule_id?: string } = {
      statutes: formData.statutes,
      key_points: formData.key_points.split(','), // 假设 key_points 是以逗号分隔的字符串
      department: formData.department.split(','), // 假设 department 也是以逗号分隔的字符串
      description: formData.description,
    };

    // 如果是编辑模式，添加 audit_rule_id
    if (isEdit) {
      auditData.audit_rule_id = formData.audit_rule_id;
    }

    // 调用 API 函数，传入转换后的数据
    if (isEdit) {
      await updateAudit(auditData as AuditData & { audit_rule_id: string }); // 使用类型断言
    } else {
      await createAudit(auditData);
    }

    loadAudits();
    setIsOpen(false);
  };

  const handleDelete = async (auditId: string) => {
    await deleteAudit(auditId);
    loadAudits();
  };
  const handleAddStatute = () => {
    setFormData({
      ...formData,
      statutes: [
        ...formData.statutes,
        { clause_number: '', section: '', content: '' },
      ],
    });
  };

  const handleRemoveStatute = (index: number) => {
    setFormData({
      ...formData,
      statutes: formData.statutes.filter((_, i) => i !== index),
    });
  };

  return (
    <div className="p-4">
      <h1 className="mb-4 text-3xl font-bold">审计规则</h1>
      <button
        className="mb-4 rounded bg-blue-500 px-4 py-2 text-white"
        onClick={() => handleOpenModal()}
      >
        新增
      </button>
      <Dialog
        open={isOpen}
        onClose={handleCloseModal}
        className="relative z-50"
      >
        <div className="fixed inset-0 bg-black/30" aria-hidden="true"></div>
        <Dialog.Panel className="fixed inset-0 flex items-center justify-center p-4">
          <div className="mx-auto max-w-md space-y-4 rounded bg-white p-6">
            <Dialog.Title
              as="h3"
              className="text-lg font-medium leading-6 text-gray-900"
            >
              审计规则明细
            </Dialog.Title>
            {formData.statutes.map((statute, index) => (
              <div key={index} className="space-y-2">
                <input
                  className="w-full border p-2"
                  type="text"
                  name={`statutes.clause_number.${index}`}
                  placeholder="Clause Number"
                  value={statute.clause_number}
                  onChange={(e) => handleChange(e, index, 'clause_number')}
                />
                <input
                  className="w-full border p-2"
                  type="text"
                  name={`statutes.section.${index}`}
                  placeholder="Section"
                  value={statute.section}
                  onChange={(e) => handleChange(e, index, 'section')}
                />
                <textarea
                  className="w-full border p-2"
                  name={`statutes.content.${index}`}
                  placeholder="Content"
                  value={statute.content}
                  onChange={(e) => handleChange(e, index, 'content')}
                />
                <button
                  className="rounded bg-red-500 px-2 py-1 text-white"
                  onClick={() => handleRemoveStatute(index)}
                >
                  删除条款
                </button>
              </div>
            ))}
            <button
              className="rounded bg-green-500 px-2 py-1 text-white"
              onClick={handleAddStatute}
            >
              添加条款
            </button>
            <input
              className="w-full border p-2"
              type="text"
              name="key_points"
              placeholder="Key Points"
              value={formData.key_points}
              onChange={handleChange}
            />
            <input
              className="w-full border p-2"
              type="text"
              name="department"
              placeholder="Department"
              value={formData.department}
              onChange={handleChange}
            />
            <textarea
              className="w-full border p-2"
              name="description"
              placeholder="Description"
              value={formData.description}
              onChange={handleChange}
            />
            <div className="flex justify-end gap-4">
              <button
                className="rounded bg-gray-500 px-4 py-2 text-white"
                onClick={handleCloseModal}
              >
                取消
              </button>
              <button
                className="rounded bg-blue-500 px-4 py-2 text-white"
                onClick={handleSubmit}
              >
                确定
              </button>
            </div>
          </div>
        </Dialog.Panel>
      </Dialog>
      <table className="w-full">
        <thead>
          <tr className="bg-gray-200">
            <th className="p-2">审计规则ID</th>
            <th className="p-2">关键要点</th>
            <th className="p-2">适合部门</th>
            <th className="p-2">简述</th>
            <th className="p-2">操作</th>
          </tr>
        </thead>
        <tbody>
          {audits.map((audit, index) => (
            <tr key={index} className="border-b">
              <td className="p-2">{audit.audit_rule_id}</td>
              <td className="p-2">{audit.key_points}</td>
              <td className="p-2">{audit.department}</td>
              <td className="p-2">{audit.description}</td>
              <td className="flex gap-2 p-2">
                <button
                  className="rounded bg-green-500 px-2 py-1 text-white"
                  onClick={() => handleOpenModal(true, audit.audit_rule_id)}
                >
                  更新
                </button>
                <button
                  className="rounded bg-red-500 px-2 py-1 text-white"
                  onClick={() => handleDelete(audit.audit_rule_id)}
                >
                  删除
                </button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

export default Audit;
